// pages/giftSel/giftgiftSel.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 50,
    page: 1,
    total_page: 0,
    items: [], //列表
    hasMore: true,
    total_num: 0, //选择提货商品总数
    addressCol: true,
    machineNum: '', //机柜号
    isLoadData: false, //是否已加载酒柜数据
    sku_code: ''
  },

  onLoad: function(options) {
    if (options.sku_code) {
      this.setData({
        sku_code: options.sku_code
      })
    }
    this.setData({
      items: [],
      page: 1,
      total_page: 0,
      total_num: 0,
      hasMore: true,
      addressCol: true
    })
    this.wineList();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  //页面上拉触底
  onReachBottom: function(e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function() {
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },

  //酒柜列表
  wineList: function() {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit,
        status: 1
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function(res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          resultList = that.doData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.items.concat(resultList)
          }
          let num = itemData.filter(function(item, index) {
            return item.sku_code == that.data.sku_code
          })
          if (num.length > 0) {
            let index = itemData.indexOf(num[0]);

            if (index >= 0) {
              num[0].current_num = 1;
              itemData.splice(index, 1);
              itemData.unshift(num[0]);
              that.setData({
                total_num: 1
              })
            }
          }

          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            items: itemData,
            isLoadData: true
          });

        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function(fail) {
        that.setData({
          isLoadData: true
        });
        wx.hideLoading();
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //处理数据
  doData: function(list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: list[i].num,
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

  //提交
  confirmOrder: function() {
    var total_num = this.data.total_num;
    if (total_num >= 1) {
      this.setData({
        addressCol: false
      })
    } else {
      util.showError("请选择商品");
    }
  },

  //输入柜机号弹框
  machineNum: function(e) {
    this.setData({
      machineNum: e.detail.value.replace(/\s+/g, '')
    })
  },

  //隐藏地址
  hiddenAddress: function() {
    this.setData({
      addressCol: true,
      machineNum: ''
    })
  },

  //增加
  addNum: function(e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num < info.num) {
      that.total_num(1)
      info.current_num = (info.current_num + 1)
      var items = that.data.items
      items[i] = info;
      that.setData({
        items: items
      })
    }else{
      util.showError("库存不足，请购买后再添加");
    }

  },
  //减少
  minusNum: function(e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num >= 1) {
      that.total_num(2)
      info.current_num = (info.current_num - 1)
      var items = that.data.items
      items[i] = info;
      that.setData({
        items: items
      })
    }
  },

  //总数量
  total_num: function(type = 1) {
    var total_num = this.data.total_num;
    this.setData({
      total_num: (type == 1) ? (total_num + 1) : (total_num - 1)
    })
  },


  //确认配送
  submit: function(e) {
    var pickup_type = e.currentTarget.dataset.type
    var that = this;
    var items = that.data.items;
    var params = new Object()
    params.use_type = 1;
    var total_num = this.data.total_num;
    if (total_num < 1) {
      util.showError("请选择商品");
      return;
    }

    params.record = [];
    var list = [];
    for (var i = 0; i < items.length; i++) {
      if (items[i].current_num > 0) {
        var box = {};
        box.sku_code = items[i].sku_code
        box.num = items[i].current_num
        list.push(box);
      }
    }
    params.record = JSON.stringify(list)

    api.POST({
      params: params,
      url: app.globalData.base_url + 'winecabinet/use',
      success: function(res) {
        if (res.data.code) {
          util.showError(res.data.message)
        } else {
          that.setData({
            addressCol: true,
            machineNum: ''
          })

          if (pickup_type == 1) {
            var qrcode_image = res.data.data.result.qrcode_image
            wx.redirectTo({
              url: '../pickUpCode/pickUpCode?qrcode_image=' + qrcode_image,
            })
          } else if (pickup_type == 2) {
            var pickupCabinetNumber = res.data.data.result.pickupCabinetNumber
            wx.redirectTo({
              url: '../pickUpSuccessful/pickUpSuccessful?oid=' + res.data.data.result.oid + '&pickupCabinetNumber=' + JSON.stringify(pickupCabinetNumber),
            })
          }
        }
      },
      fail: function(fail) {
        util.showError("网络错误");
      }
    })
  },


})